package com.umeox.moto.common.utils;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;

/**
 * Created by zl on 2018/4/12.
 */

public class SystemUtils {


    /**
     * 修改语言设置
     *
     * @param code
     */
    public static void setLocalLanguage(Object code) {
        try {
            Class<?> activityManagerNative = Class.forName("android.app.ActivityManagerNative");

            Object am = activityManagerNative.getMethod("getDefault").invoke(activityManagerNative);

            Object config = am.getClass().getMethod("getConfiguration").invoke(am);

            config.getClass().getDeclaredField("locale").set(config, code);
            config.getClass().getDeclaredField("userSetLocale").setBoolean(config, true);
            am.getClass().getMethod("updateConfiguration", android.content.res.Configuration.class).invoke(am, config);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 设置数据流量开关
     *
     * @param enable
     * @param context
     * @throws Exception
     */
    @SuppressLint("NewApi")
    public static void setDataEnabled(Context context, boolean enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setDataEnabledHighApi(context, enable);
            return;
        }

        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressLint("PrivateApi")
            Method setDataEnabled = connectivityManager.getClass().getDeclaredMethod("setMobileDataEnabled", boolean.class);
            setDataEnabled.invoke(connectivityManager, enable);
            Log.e("SystemUtils", "setDataEnabled suc");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("SystemUtils", "setDataEnabled exception");
        }
    }

    /**
     * 设置数据流量开关
     *
     * @param enable
     * @param context
     * @throws Exception
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void setDataEnabledHighApi(Context context, boolean enable) {
        try {
            TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            telephonyService.setDataEnabled(enable);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("SystemUtils", "setDataEnabled exception");
        }
    }


    /**
     * 获取数据流量开关 需要系统权限
     *
     * @param context
     * @return
     * @throws Exception
     */
    @SuppressLint("NewApi")
    public static boolean getDataEnabledHighApi(Context context) {
        boolean enabled = false;
        try {
            TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            enabled = telephonyService.isDataEnabled();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return enabled;
    }


    /**
     * 获取数据流量开关 需要系统权限
     *
     * @param context
     * @return
     * @throws Exception
     */
    @SuppressLint("NewApi")
    public static boolean getDataEnabled(Context context) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return getDataEnabledHighApi(context);
        }

        boolean enabled = false;
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressLint("PrivateApi")
            Method getDataEnabled = connectivityManager.getClass().getDeclaredMethod("getMobileDataEnabled");
            enabled = (Boolean) getDataEnabled.invoke(connectivityManager);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return enabled;
    }

    /**
     * @param context
     * @param mode    0:标准模式、1:仅振动、2:仅响铃 3：静音
     */
    public static void setRingerMode(Context context, int mode) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        switch (mode) {
            case 0:
                audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
                        AudioManager.VIBRATE_SETTING_ON);
                audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
                        AudioManager.VIBRATE_SETTING_ON);
                break;
            case 1:

                audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
                        AudioManager.VIBRATE_SETTING_ON);
                audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
                        AudioManager.VIBRATE_SETTING_ON);
                break;
            case 2:

                audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
                        AudioManager.VIBRATE_SETTING_OFF);
                audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
                        AudioManager.VIBRATE_SETTING_OFF);

                break;
            case 3:
                audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                break;
        }
    }


    /**
     * 根据电话号码取得联系人姓名
     */
    public static String getContactNameByPhoneNumber(Context context, String address) {
        String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER};

        Cursor cursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection,
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
                        + address + "'",
                null,
                null);

        if (cursor == null) {
            return null;
        }
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            // 取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String name = cursor.getString(nameFieldColumnIndex);
            return name;
        }
        return null;
    }


    /**
     * 忘记某一个wifi密码
     *
     * @param wifiManager
     * @param targetSsid
     */
    public static void removeWifiBySsid(WifiManager wifiManager, String targetSsid) {
        Log.d("TAG", "try to removeWifiBySsid, targetSsid=" + targetSsid);
        List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();

        for (WifiConfiguration wifiConfig : wifiConfigs) {
            String ssid = wifiConfig.SSID;
            Log.d("TAG", "removeWifiBySsid ssid=" + ssid);
            if (ssid.equals(targetSsid)) {
                Log.d("TAG", "removeWifiBySsid success, SSID = " + wifiConfig.SSID + " netId = " + String.valueOf(wifiConfig.networkId));
                boolean result = wifiManager.removeNetwork(wifiConfig.networkId);
                Log.e("TAG", "result:" + result);
            }
        }
    }


    public static boolean getVoletState(Context context) {
        boolean result = false;
        Cursor cursor = null;
        try {
            Uri CONTENT_URI = Uri.parse("content://settings/global");
            cursor = context.getContentResolver().query(CONTENT_URI, null, "name = ?", new String[]{"volte_vt_enabled"}, "");
            if (cursor != null && cursor.moveToNext()) {
                //result = cursor.getInt(cursor.getColumnIndex("count"));
                Log.e("PhoneInfo", "value:" + cursor.getString(cursor.getColumnIndex("value")));
                result = "1".equals(cursor.getString(cursor.getColumnIndex("value")));
                Log.e("PhoneInfo", "result:" + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return result;
    }

    public static void setVolte(Context context, boolean enable) {
        try {
            @SuppressLint({"NewApi", "LocalSuppress"})
            SubscriptionManager subManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
            Class<? extends SubscriptionManager> sunClass = subManager.getClass();
            Method method1 = sunClass.getDeclaredMethod("getDefaultVoicePhoneId");
            method1.setAccessible(true);
            int phoneid = (Integer) method1.invoke(subManager);

            Class<?> clazz = Class.forName("com.android.ims.ImsManager");

            Constructor<?> ct = clazz.getDeclaredConstructor(Context.class, int.class);
            ct.setAccessible(true);

            Object obj = ct.newInstance(context, phoneid);

            Method method = clazz.getDeclaredMethod("setAdvanced4GMode", boolean.class);
            method.setAccessible(true);

            method.invoke(obj, enable);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }


    public static boolean isConnectInternet(Context context) {
        ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conManager != null) {
            try {

                NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
                if (networkInfo != null) {
                    return networkInfo.isAvailable();
                }
            } catch (Exception var3) {
                Log.e("SystemUtils", "isConnectInternet: ", var3);
            }
        }

        return false;
    }

    public static void setAirPlaneMode(Context context, boolean enable) {
        if ((enable && isAirplaneModeOn(context)) || (!enable && !isAirplaneModeOn(context))) {
            return;
        }

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
            Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0);
        } else {
            Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
        }
        Intent intent = new Intent("com.umeox.watch.intent.action.AIRPLANE_MODE");
        intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.AirplaneMode"));
        intent.putExtra("state", enable ? 1 : 0);
        context.sendBroadcast(intent);

    }

    public static boolean isAirplaneModeOn(Context context) {
        return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }


    public static boolean isRuLanguage() {
        return Locale.getDefault().getLanguage().equals(new Locale("ru").getLanguage());
    }

    /**
     * 关闭屏幕 ，其实是使系统休眠
     */
    public static void goToSleep(Context context) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        try {
            powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public static String getLocale() {
        Locale l = Locale.getDefault();
        return l.getLanguage().toLowerCase();
    }
}
